import {login, whoAmI, loginOut} from '../services/user.js';
// 用户相关数据
export default{
	namespaced: true,
	state: {
		// 用户数据
		user: null,
		// 订阅
		subscriber: [],
		// 历史观看视频数据
		historyVideo: [],
		// 历史观看频道
		historyChannel: []
	},
	mutations: {
		// 获取用户登录信息
		loginUser(state, payload){
			state.user = payload;
		},
		// 获取用户订阅数据
		getSubscriber(state, payload){
			state.subscriber = payload;
		},
		// 添加历史观看视频
		setHistoryVideo(state, payload){
			let target = state.historyVideo,
					has = target.findIndex((item,index)=>item.id==payload.id)
			
			if(has != -1) target.splice(has, 1);
			target.push(payload);
			sessionStorage.setItem('historyVideo', JSON.stringify(target));
		},
		// 添加历史观看类别
		setHistoryChannel(state, payload){
			let target = state.historyChannel,
					has = target.findIndex((item,index)=>item.id==payload.id)
			
			if(has != -1) target.splice(has, 1);
			target.push(payload);
			sessionStorage.setItem('historyChannel', JSON.stringify(target));
		},
		// 获取历史观看视频
		getHistoryVideo(state){
			let data = sessionStorage.getItem('historyVideo');
			state.historyVideo = JSON.parse(data || [])
		},
		// 获取历史观看类别
		getHistoryChannel(state){
			let data = sessionStorage.getItem('historyChannel');
			state.historyChannel = JSON.parse(data || '[]')
		}
	},
	actions: {
		// 登录
		async login(context, payload){
			context.commit('global/setLoading', true, {root: true});
			let resp = await login(payload);
			context.commit('loginUser', resp);
			context.commit('global/setLoading', false, {root: true});
		},
		// 刷新或打开网页时根据token返回当前用户信息
		async whoAmI(context){
			context.commit('global/setLoading', true, {root: true});
			let resp = await whoAmI();
			context.commit('loginUser', resp);
			context.commit('global/setLoading', false, {root: true});
		},
		// 退出登录，并清掉数据
		loginOut(context){
			context.commit('global/setLoading', true, {root: true});
			loginOut();
			context.commit("loginUser", null)
			context.commit('global/setLoading', false, {root: true});
		}
	}
}